package com.woshua.discrollview.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ScrollView;

import com.woshua.discrollview.view.callback.DiScrollableInterface;

/*
* 监听滑动
* */
public class DiScrollView extends ScrollView {

    private DiScrollViewContent mContent;

    public DiScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        View content=getChildAt(0);

        mContent = (DiScrollViewContent) content;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        View first = mContent.getChildAt(0);
        first.getLayoutParams().height = getHeight();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        int scrollViewHeight = getHeight();

        for (int i = 0; i < mContent.getChildCount(); i++) {
            View child = mContent.getChildAt(i);

            if(!(child instanceof DiScrollableInterface)){
                continue;
            }

            DiScrollableInterface diScrollableInterface= (DiScrollableView) child;
            //child距离scrollview高度
            int discrollvableTop = child.getTop();
            int discrollvableHeight = child.getHeight();


            int discrollvableAbsoluteTop = discrollvableTop - t;
            if(discrollvableAbsoluteTop<=scrollViewHeight){
                int visibleGap = scrollViewHeight - discrollvableAbsoluteTop;
                diScrollableInterface.onScrollable(clamp(visibleGap/(float)discrollvableHeight, 1f,0f));
            }else{
                diScrollableInterface.onResetDiScrollable();
            }
        }
    }

    public static float clamp(float value, float max, float min){
        return Math.max(Math.min(value, max), min);
    }
}
